package com.aix.demo.activity;

import java.util.Random;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.TextView;

import com.aix.demo.R;

public class AsyncTaskActivity extends Activity {
	
	private TextView textview1;
	
	private TextView textview2;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.activity_fake_async_task);
		
		textview1 = (TextView) findViewById(R.id.textview1);
		textview2 = (TextView) findViewById(R.id.textview2);
		
		new FakeAsyncTask(textview1).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
		new FakeAsyncTask(textview2).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
	}

	public class FakeAsyncTask extends AsyncTask<Void, Integer, Void> {
		
		private TextView textview;
		
		public FakeAsyncTask(TextView textview) {
			super();
			
			this.textview = textview;
		}

		@Override
		protected Void doInBackground(Void... params) {
			Random random = new Random();
			for (int i = 1; i <= 100; ++i) {
				// 100 ~ 500ms
				long sleepTime = random.nextInt(400) + 101;
				try {
					Thread.sleep(sleepTime);
					
					publishProgress(i);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			return null;
		}

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
		}

		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
			textview.setText(values[0].toString());
		}

		@Override
		protected void onCancelled(Void result) {
			// TODO Auto-generated method stub
			super.onCancelled(result);
		}

		@Override
		protected void onCancelled() {
			// TODO Auto-generated method stub
			super.onCancelled();
		}
		
	}
}
